package com.echo.servlet.UserServlet;

import com.echo.entity.User;
import com.echo.service.UserService;
import com.echo.servlet.BaseServlet;
import com.echo.util.BusinessException;
import com.echo.util.SessionUtils;
import com.echo.util.StringUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import java.util.HashMap;

@WebServlet("/profile/update")
public class UpdateProfileServlet extends BaseServlet {
    private final UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 设置编码（兼容POST提交）+ 校验登录
        setRequestEncoding(request);
        if (!checkLogin(request, response)) {
            return;
        }

        // 2. 获取表单参数
        User loginUser = SessionUtils.getCurrentUser(request);
        Integer userId = loginUser.getId();
        String email = "";
        String nickname = "";
        String avatar = loginUser.getAvatar(); // 默认使用当前头像

        try {
            // 检查请求是否为multipart类型
            if (ServletFileUpload.isMultipartContent(request)) {
                // 创建文件上传工厂和解析器
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("UTF-8");

                // 解析请求
                List<FileItem> items = upload.parseRequest(request);
                // 创建参数映射
                HashMap<String, String> params = new HashMap<>();

                // 处理表单字段
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        // 普通表单字段
                        String fieldName = item.getFieldName();
                        String fieldValue = item.getString("UTF-8");
                        params.put(fieldName, fieldValue);
                    }
                }

                // 从映射中获取表单数据
                email = params.getOrDefault("email", "");
                nickname = params.getOrDefault("nickname", "");
                
                // 保留表单提交的头像信息（可能是新上传的或原始的）
                if (params.containsKey("avatar") && !params.get("avatar").isEmpty()) {
                    avatar = params.get("avatar");
                }
                
                // 不强制要求填写邮箱和昵称
                // 只有当用户明确修改了字段且不为空时才更新
                if (StringUtils.isEmpty(email)) {
                    email = loginUser.getEmail();
                }
                
                if (StringUtils.isEmpty(nickname)) {
                    nickname = loginUser.getNickname();
                }
            } else {
                // 非multipart请求，直接使用getParameter
            email = request.getParameter("email");
        nickname = request.getParameter("nickname");
        
        // 只有在用户明确上传了新头像文件时才更新头像
        String newAvatar = request.getParameter("avatar");
        if (newAvatar != null && !newAvatar.equals(loginUser.getAvatar())) {
            avatar = newAvatar;
        }
        
        // 不强制要求填写邮箱和昵称
        // 只有当用户明确修改了字段且不为空时才更新
        if (email == null || StringUtils.isEmpty(email)) {
            email = loginUser.getEmail();
        }
        
        if (nickname == null || StringUtils.isEmpty(nickname)) {
            nickname = loginUser.getNickname();
        }
            }

            // 3. 封装User对象
            User user = new User();
            user.setId(userId);
            user.setEmail(email);
            user.setNickname(nickname);
            user.setAvatar(avatar);

            // 4. 调用Service修改资料
            userService.updateProfile(user);
            
            // 更新Session中的用户信息（同步展示页数据）
            loginUser.setEmail(email);
            loginUser.setNickname(nickname);
            loginUser.setAvatar(avatar);
            request.getSession().setAttribute("loginUser", loginUser);

            request.getSession().setAttribute("successMsg", "资料修改成功！");
            response.sendRedirect(request.getContextPath() + "/profile-show"); // 修改成功后重定向到展示页
        } catch (BusinessException e) {
            // 业务异常（如邮箱已存在）
            request.setAttribute("errorMsg", e.getMessage());
            // 回显用户输入的数据
            User user = new User();
            user.setId(userId);
            user.setEmail(email);
            user.setNickname(nickname);
            user.setAvatar(avatar);
            request.setAttribute("user", user);
            forward(request, response, "/profile.html");
        } catch (Exception e) {
            // 系统异常
            log("更新资料失败: " + e.getMessage());
            request.setAttribute("errorMsg", "系统异常，请稍后重试！");
            // 回显用户输入的数据
            User user = new User();
            user.setId(userId);
            user.setEmail(email);
            user.setNickname(nickname);
            user.setAvatar(avatar);
            request.setAttribute("user", user);
            forward(request, response, "/profile.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}